<template>
  <view class="questionnaire-container" v-if="visible">
    <view class="questionnaire-mask"></view>
    <view class="questionnaire-paper">
      <!-- 右上角关闭按钮 -->
      <view class="close-btn" @click="handleCloseConfirm">
        <text class="iconfont close-icon">×</text>
      </view>
      
      <!-- 顶部装饰线 -->
      <view class="paper-decoration-top"></view>
      
      <!-- 问卷内容 -->
      <view class="paper-content">
        <!-- 标题 -->
        <view class="paper-title">{{ currentQuestionnaire.title }}</view>
        <view class="paper-subtitle">{{ currentQuestionnaire.description }}</view>
        
        <!-- 问卷题目区域 -->
        <view class="questions-container">
          <view 
            v-for="(question, qIndex) in currentQuestions" 
            :key="qIndex" 
            class="question-item"
          >
            <text class="question-number">{{ getQuestionNumber(qIndex) }}.</text>
            <view class="question-content">
              <text class="question-text">{{ question.text }}</text>
              
              <!-- 单选题目 -->
              <radio-group 
                v-if="question.type === 'radio'" 
                @change="(e) => handleRadioChange(question.id, e.detail.value)"
                class="option-group"
              >
                <view 
                  v-for="(option, oIndex) in question.options" 
                  :key="oIndex" 
                  class="option-item"
                >
                  <label class="option-label">
                    <radio :value="String(option.value)" :checked="answers[question.id] === option.value" />
                    <text class="option-text">{{ option.label }}</text>
                  </label>
                </view>
              </radio-group>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部装饰线 -->
      <view class="paper-decoration-bottom"></view>
      
      <!-- 分页控制 -->
      <view class="page-control">
        <button 
          v-if="currentPage > 0" 
          @click="prevPage" 
          class="control-btn prev-btn"
        >上一页</button>
        
        <button 
          v-if="currentPage < totalPages - 1" 
          @click="nextPage" 
          class="control-btn next-btn"
          :disabled="!isCurrentPageComplete"
        >下一页</button>
        
        <button 
          v-if="currentPage === totalPages - 1" 
          @click="handleSubmit" 
          class="control-btn submit-btn"
          :disabled="!isAllComplete"
        >提交评估</button>
      </view>
    </view>
  </view>
</template>

<script>
import { QUESTIONNAIRE_SETS } from "@/data/data.js"

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
	questionnaireId:{
		type:Number,
		default:0
	}
  },
  data() {
    return {
      currentPage: 0,
      answers: {},
      questionsPerPage: 20, // 每页题目数量
      questionnaires: QUESTIONNAIRE_SETS || [],
      currentQuestionnaire: {},
      paginatedQuestions: []
    }
  },
  watch: {
      questionnaireId(newVal) {
        if (this.visible) {
          this.selectQuestionnaire(newVal)
        }
      }
    },
  computed: {
    currentQuestions() {
      return this.paginatedQuestions[this.currentPage] || []
    },
    totalPages() {
      return this.paginatedQuestions.length
    },
    isCurrentPageComplete() {
      return this.currentQuestions.every(q => {
        return this.answers[q.id] !== undefined && this.answers[q.id] !== ''
      })
    },
    isAllComplete() {
      return Object.values(this.answers).every(v => v !== undefined && v !== '')
    }
  },
  created() {
    this.selectQuestionnaire(this.questionnaireId)
  },
  methods: {
    selectQuestionnaire(questionnaireId) {
      if (this.questionnaires.length === 0) {
        console.error('No questionnaires available')
        return
      }
      this.currentQuestionnaire = this.questionnaires[questionnaireId]
      this.initPages(this.currentQuestionnaire.questions)
    },
    
    initPages(questions) {
      this.paginatedQuestions = []
      this.currentPage = 0
      this.answers = {}
      
      // 分页处理
      for (let i = 0; i < questions.length; i += this.questionsPerPage) {
        this.paginatedQuestions.push(questions.slice(i, i + this.questionsPerPage))
      }
      
      // 初始化答案
      questions.forEach(q => {
        this.$set(this.answers, q.id, '')
      })
    },
    
    getQuestionNumber(qIndex) {
      return this.currentPage * this.questionsPerPage + qIndex + 1
    },
    
    handleRadioChange(questionId, value) {
      this.answers[questionId] = parseInt(value)
    },
    
    prevPage() {
      if (this.currentPage > 0) {
        this.currentPage--
      }
    },
    
    nextPage() {
      if (this.isCurrentPageComplete && this.currentPage < this.totalPages - 1) {
        this.currentPage++;
      } else {
        uni.showToast({
          title: '请完成当前页所有题目',
          icon: 'none'
        })
      }
    },
    
    handleCloseConfirm() {
      uni.showModal({
        title: '提示',
        content: '您确定要退出评估吗？未完成的评估将不会被保存',
        success: (res) => {
          if (res.confirm) {
            this.handleClose()
          }
        }
      })
    },
    
    handleSubmit() {
      if (!this.isAllComplete) {
        uni.showToast({
          title: '请完成所有题目',
          icon: 'none'
        })
        return
      }
      
      // 计算总分
      let totalScore = 0
      for (const key in this.answers) {
        totalScore += this.answers[key] || 0
      }
      
      // 评估结果
      const { thresholds, levels } = this.currentQuestionnaire.scoring
      let resultIndex = 0
      while (resultIndex < thresholds.length && totalScore >= thresholds[resultIndex]) {
        resultIndex++
      }
      const assessment = levels[resultIndex]
      
      this.$emit('submit', {
        questionnaireId: this.currentQuestionnaire.id,
        questionnaireTitle: this.currentQuestionnaire.title,
        answers: this.answers,
        totalScore,
        assessment
      })
      this.handleClose()
    },
    
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
      this.selectQuestionnaire(this.questionnaireId)
    }
  }
}
</script>

<style lang="scss" scoped>
.questionnaire-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  min-width:300px; 
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.questionnaire-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.questionnaire-paper {
  position: relative;
  width: 90%;
  max-width: 800rpx;
  max-height: 90vh;
  background-color: #f8f5f0;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.15);
  border: 1px solid #e0d8c8;
  z-index: 1000;
  
  background-image: 
    linear-gradient(rgba(255,255,255,0.3) 1px, transparent 1px),
    linear-gradient(90deg, rgba(220,210,190,0.2) 1px, transparent 1px);
  background-size: 100% 24rpx, 24rpx 100%;
}

.close-btn {
  position: absolute;
  top: 32rpx;
  right: 32rpx;
  width: 64rpx;
  height: 64rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 1001;
  transition: all 0.3s ease;
  border: 2rpx solid rgba(0, 0, 0, 0.05);
}

.close-btn:active {
  transform: scale(0.92);
  background: rgba(255, 255, 255, 0.8);
}

.close-icon {
  font-size: 40rpx;
  color: rgba(0, 0, 0, 0.6);
  transition: all 0.2s ease; /* 确保有颜色过渡动画 */
  font-weight: 300;
  margin-top: -4rpx;
}

/* 悬停效果 */
@media (hover: hover) {
  .close-btn:hover {
    transform: scale(1.5);
	font-weight: bold;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
  }
  
  .close-btn:hover .close-icon {
    color: #ff4d4d; /* 主红色 */
    text-shadow: 0 2rpx 4rpx rgba(255, 77, 77, 0.2); /* 增加红色光晕 */
  }
}

/* 增加按压状态颜色加深 */
.close-btn:active .close-icon {
  color: #ff1a1a !important;
}

.paper-decoration-top,
.paper-decoration-bottom {
  height: 8rpx;
  background: linear-gradient(90deg, 
    transparent, 
    rgba(200, 180, 150, 0.5), 
    transparent);
  margin: 15rpx 0;
  border-radius: 6rpx;
}

.paper-title {
  font-size: 36rpx;
  font-weight: 600;
  text-align: center;
  margin: 10rpx 0 15rpx;
  color: #4a3c2a;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  position: relative;
  letter-spacing: 1rpx;
}

.paper-subtitle {
  font-size: 26rpx;
  text-align: center;
  margin-bottom: 20rpx;
  color: #8b7d5e;
}

.questions-container {
  padding: 10rpx 0;
  max-height: 65vh;
  overflow-y: auto;
}

.question-item {
  display: flex;
  margin-bottom: 30rpx;
  position: relative;
  padding-bottom: 20rpx;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 1rpx;
    background: linear-gradient(90deg, 
      transparent, 
      rgba(160, 140, 110, 0.3), 
      transparent);
  }
}

.question-number {
  font-weight: 600;
  margin-right: 12rpx;
  color: #8b7d5e;
  font-size: 30rpx;
  min-width: 40rpx;
  text-align: right;
}

.question-content {
  flex: 1;
  width: 100%;
}

.question-text {
  display: block;
  margin-bottom: 20rpx;
  font-size: 30rpx;
  color: #4a3c2a;
  line-height: 1.4;
  font-weight: 500;
}

.option-group {
  width: 100%;
}

.option-item {
  margin-bottom: 12rpx;
  width: 90%;
}

.option-label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #5a4a3a;
  padding: 12rpx 16rpx;
  transition: all 0.2s;
  background: rgba(255,255,255,0.7);
  border-radius: 8rpx;
  border: 1rpx solid rgba(160, 140, 110, 0.2);
  
  &:active {
    transform: scale(0.98);
    background: rgba(200,190,170,0.2);
  }
  
  radio {
    margin-right: 10px;
    transform: scale(0.9);
  }
  
  .option-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
  }
}

.page-control {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  padding-top: 20rpx;
}

.control-btn {
  padding: 16rpx 40rpx;
  font-size: 30rpx;
  border-radius: 50rpx;
  background-color: #8b7d5e;
  color: white;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(139, 125, 94, 0.2);
  transition: all 0.2s;
  font-weight: 500;
  
  &:active {
    transform: scale(0.96);
    opacity: 0.9;
  }
  
  &[disabled] {
    opacity: 0.6;
  }
  
  &.prev-btn {
    background-color: #b0a58e;
    color: #4a3c2a;
  }
  
  &.submit-btn {
    background-color: #6b8e23;
    box-shadow: 0 4rpx 12rpx rgba(107, 142, 35, 0.3);
  }
}
</style>